<?php


namespace app\admin\model;


use app\common\service\ReplyService;
use app\sys\service\GateCli;
use Kqtec\IpLocationZh\Ip;
use think\Db;
use think\Exception;
use think\facade\Log;

class UserList
{
    /**
     * @param $staffId
     * @param $staffType
     * @param $search
     * @param $orderBy
     * @param int $page
     * @param int $limit
     * @return array
     * 用户列表
     */
    public static function userLists($staffId, $staffType, $search, $orderBy, $page = 1, $limit = 10): array
    {
        $countLog = "sum(if(cl.status = 0 and cl.send_to = 'staff',1,0)) as count_log";

        $listSql = Chat::alias('a')
            ->field("a.id as chat_id,a.user_icon,a.user_name,a.user_id,a.user_agent
            ,a.update_time
            ,if(a.last_info is null,'',a.last_info) as last_info
            ,a.last_info_status,a.user_no,a.send_to,a.collect,cl.user_agent,{$countLog}")
            ->leftjoin("ic_chat_log cl", "cl.chat_id = a.id")
            ->leftjoin("ic_user iu", "iu.id = a.user_id")
            ->where("a.staff_id", $staffId);
        if ($orderBy == 0) {
            $listSql = $listSql->order("a.status,a.update_time desc");
        } else {
            $listSql = $listSql->order("a.status,a.update_time");
        }
        $listSql = $listSql->group("a.id");

        $listCSql = Chat::alias('a')
            ->leftjoin("ic_user iu", "iu.id = a.user_id")
            ->where("a.staff_id", $staffId);

        if ($staffType == 1) {
            $listSql = $listSql->where("iu.mobile", "<>", "");
            $listCSql = $listCSql->where("iu.mobile", "<>", "");
        } else {
            $listSql = $listSql->where("iu.mobile", "");
            $listCSql = $listCSql->where("iu.mobile", "");
        }

        if (!empty($search)) {
            $listSql = $listSql->whereLike("a.user_name", "%{$search}%");
            $listCSql = $listCSql->where("a.user_name", "%{$search}%");
        }

        $listCount = $listCSql->count();
        $listDate = $listSql->page($page, $limit)->select();

        $cli = new GateCli();
        foreach ($listDate as $key => $v) {
            $listDate[$key]["user_show"] = $cli->userStatus($v["user_no"]);
            $listDate[$key]["count_log"] = (int)$v["count_log"];
        }
        return listDate($listDate, $listCount);
    }

    /**
     * @param $staffId
     * @return Staff
     * 获取客服信息数据
     */
    public static function staffNews($staffId)
    {

        $isMemSql = "if(c.user_mobile > 0 && c.last_info_status = 0 && c.send_to = 'staff',1,0)";
        $noMemSql = "if(c.user_mobile = 0 && c.last_info_status = 0 && c.send_to = 'staff',1,0)";

        $staffInfo = Staff::alias("s")
            ->field("s.staff_name,s.staff_no,s.icon,sum({$isMemSql}) as is_mem_sum,sum({$noMemSql}) as no_mem_sum,s.status,s.is_reply_auto,s.reply_auto_time")
            ->leftJoin("ic_chat c", "c.staff_id = s.id")
            ->where("s.id", $staffId)->find();

        $cli = new GateCli();
        $staffInfo["user_show"] = $cli->staffStatus($staffInfo["staff_no"]);
        return $staffInfo;
    }

    /**
     * @param $staffId
     * @param $userId
     * @param $chatId
     * @param $chatLogId
     * @param int $page
     * @param int $limit
     * @return array
     * 获取聊天消息
     */
    public static function getInfo($staffId, $userId, $chatId, $chatLogId, $page = 0, $limit = 10): array
    {

        $g = new GateCli();

        $logSql = ChatLog::alias("c")
            ->field("ss.pxs_id as store_id,c.id,c.chat_type,c.chat_id, c.send_to,
            IFNULL(ss.url,'') as store_url,IFNULL(ss.title,'') as store_title,IFNULL(ss.img,'') as store_img,IFNULL(ss.address,'') as store_address,
            IFNULL(ss.industry,'') as store_industry,IFNULL(ss.cost,'') as store_cost,IFNULL(ss.pv,'') as store_pv,IFNULL(ss.rent,'') as store_rent,
            IFNUll(ss.square,'') as store_square,
            
            u.id as user_id,u.icon as user_icon,u.name as user_name,s.id as staff_id,s.staff_name,s.icon as staff_icon,c.info,c.send_to")
            ->leftJoin("ic_user u", "u.id = c.user_id")
            ->leftJoin("ic_staff s", "s.id = c.staff_id")
            ->leftJoin("ic_user_pv_log ss", "ss.id = c.store_id");
        // id
        if ($chatId) {
            $logSql = $logSql->where("c.chat_id", $chatId);
        } else {
            $logSql = $logSql->where("c.user_id", $userId)->where("c.staff_id", $staffId);
        }

        $log = $logSql->where("c.status", ">=", 0);


        $dataCount = $log->Count();
        // 从id往回找
        if ($chatLogId) {
            $log = $log->where("c.id", "<", $chatLogId)->limit($limit)->order("c.create_time desc");
        } else {
            $log = $log->page($page, $limit)->order("c.create_time desc");
        }

        $dataLog = $log->select();
        $s = new Staff();
        foreach ($dataLog as $k => $v) {
            $dataLog[$k]["staff_icon"] = $s->getIconAttr($v["staff_icon"]);
            $dataLog[$k]["type"] = ($dataLog[$k]["send_to"] ==  $g::sendTypeNo ? $g::sendTypeNo :$g::sendTypeInfo);
        }
        return listDate($dataLog, $dataCount);
    }

    /**
     * @param $chatId
     * @param $userId
     * @param $staffId
     * @param $sendTo
     * @return string
     * 修改状态
     */
    public static function upStatus($chatId, $userId, $staffId, $sendTo): string
    {
        $res = "";
        Db::startTrans();
        try {

            // 房间修改
            $Csql = Chat::where("send_to", $sendTo);
            // 记录修改
            $logSql = ChatLog::where("send_to", $sendTo);

            if ($chatId) {
                $Csql = $Csql->where("id", $chatId);
                $logSql = $logSql->where("chat_id", $chatId);
            } else {
                $Csql = $Csql->where("user_id", $userId)->where("staff_id", $staffId);
                $logSql = $logSql->where("user_id", $userId)->where("staff_id", $staffId);
            }

            // 修改成功返回1
            $updateRes = $Csql->update(["last_info_status" => 1]);
            if(!$updateRes){
                $res = "";
            }
            $logSql->update(["status" => 1]);

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            return "修改失败" . $e->getMessage();
        }
        return $res;
    }

    /**
     * @param $userId
     * @param $chatInfo
     * @param $staffInfo
     * @param $userNo
     * @param $storeId
     * @return string
     * 发送客户
     */
    public static function toUser($userId,$userNo, $chatInfo, $staffInfo, $storeId): string
    {
        $cli = new GateCli();
        Db::startTrans();
        try {
            // 客服回复 （取消自动）
            Reply::touchOffAutoReplyDelete($userNo,$staffInfo["staff_no"]);
            //是否回复
            StaffReplyCount::saveReply($staffInfo["staff_no"], $userNo,1);
            // 设备
            $deviceId = "";
            if (isset($staffInfo["device_id"])){
                $deviceId = $staffInfo["device_id"];
            }

            $res = $cli->SendToUser($staffInfo["id"], $userId, $deviceId, $storeId, $chatInfo);
            if ($res) {
                Db::rollback();
                Log::info("SendToUser:{$res}");
                return "发送失败";
            }
            ReplyService::delUserToStaffLog($userId,$staffInfo["id"]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::info("SendToUser:{$e->getMessage()}");
            return "发送异常";
        }
        return "";
    }

    /**
     * @param $ip
     * @param $data
     * @param $staffInfo
     * @param $deviceType
     * @return string
     * 发送客服
     */
    public static function toStaff($ip, $data, $staffInfo, $deviceType,$url): string
    {
        Db::startTrans();
        try {
            //判断是会员还是游客
            list($userId, $isMen) = User::addChatUser($data, $staffInfo["staff_no"], $ip,$url);
            // 添加统计数据
            StaffChatTime::addChatTime($staffInfo["staff_no"], $data["user_no"], $deviceType);
            // 自动回复 （取消自动）
            Reply::touchOffAutoReplyDelete($data["user_no"],$staffInfo["staff_no"]);
            //是否回复
            StaffReplyCount::saveReply($staffInfo["staff_no"], $data["user_no"],0);

            $staffInfo["device_id"] = get_device_type();
            $cli = new GateCli();
            // 发送消息
            $res = $cli->SendToUser(
                $staffInfo["id"],
                $userId,
                $staffInfo["device_id"],
                $data["store_id"],
                $data["chat_info"],
                1,
                $isMen,
                $staffInfo["status"]
            );
            ReplyService::appendUserToStaffLog($userId, $staffInfo["id"], $staffInfo["staff_no"], $isMen); //添加新自动回复用户发送员工日志
            if ($res) {
                Db::rollback();
                Log::info("SendToUser:{$res}");
                return "发送失败";
            }
            // 机器人 自动判断是否回复
            RobotSet::matchRe($data["user_no"], $staffInfo["staff_no"], $data["chat_info"]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::info("SendToUser:{$e->getMessage()}");
            return "发送异常";
        }
        return "";
    }


    /**
     * @param $mobile
     * @param $search
     * @param $page
     * @param $limit
     * @return array
     * 获取客服列表
     */
    public static function getList($mobile, $userNo, $search, $page, $limit): array
    {
        $countLog = "sum(if(cl.status = 0 and cl.send_to = 'user',1,0)) as count_log";

        $listSql = Chat::alias('a')
            ->field("a.id as chat_id,s.icon as staff_icon,s.staff_name,a.staff_id,a.staff_no,a.user_agent
            ,a.update_time
            ,if(a.last_info is null,'',a.last_info) as last_info
            ,a.last_info_status,a.user_no,a.send_to,a.collect,cl.user_agent,{$countLog}")
            ->leftjoin("ic_chat_log cl", "cl.chat_id = a.id")
            ->leftJoin("ic_staff s", "s.staff_no = a.staff_no");

        if($mobile){
            $listSql = $listSql->where("a.user_mobile", $mobile);
        }else{
            $listSql = $listSql->where("a.user_no",$userNo);
        }

        $listSql ->where("a.delete_time", 0)
            ->order("a.update_time desc,a.collect desc,a.last_info_status desc")
            ->group("a.id");

        $listCSql = Chat::alias('a')
            ->leftJoin("ic_staff s", "s.staff_no = a.staff_no")
            ->where("a.user_mobile", $mobile)
        ;

        if (!empty($search)) {
            $listSql = $listSql->whereLike("a.user_name", "%{$search}%");
            $listCSql = $listCSql->whereLike("a.user_name", "%{$search}%");
        }

        $listCount = $listCSql->count();
        $listDate = $listSql->page($page, $limit)->select();

        $cli = new GateCli();
        $staff = new Staff();
        foreach ($listDate as $key => $v) {

            // 机器人不需要
            if($v["staff_no"] != "PXS000000"){
                $listDate[$key]["staff_name"] = getStaffName($v["staff_name"]);
            }

            $listDate[$key]["user_show"] = $cli->staffStatus($v["user_no"]);
            $listDate[$key]["count_log"] = (int)$v["count_log"];

            $listDate[$key]["staff_icon"] = $staff->getIconAttr($v["staff_icon"]);
        }
        return listDate($listDate, $listCount);
    }
}